#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#define FIFO_NAME "fifo"
class Fifo_Creat{

public:
    Fifo_Creat(const std::string& name,const std::string& path)
    :_filename(name)
    ,_path(path)
    {
        _fifoname = _path+"/"+_filename;
        umask(0);
        int n = mkfifo(_fifoname.c_str(),0666);
        if(n<0){
            std::cout<<"make file fail!"<<std::endl;
        }
        std::cout<<"make file success!"<<std::endl;
    }
    ~Fifo_Creat(){
        int n = unlink(_fifoname.c_str());
        if(n<0){
            std::cout<<"unlink file file!"<<std::endl;
        }
        std::cout<<"unlink file success!"<<std::endl;

    }
private:
    std::string _filename;
    std::string _path;
    std::string _fifoname;
};


class Fifo_oper{

public:
    Fifo_oper(const std::string& name,const std::string& path)
    :_filename(name)
    ,_path(path)
    ,_fd(-1)
    {
        _fifoname = _path+"/"+_filename;
    }
    void OpenForRead() {
        _fd = open(_fifoname.c_str(),O_RDONLY);
        if(_fd<0)
        {
            std::cout<<"open file file!"<<std::endl;
        }
        std::cout<<"open file success!"<<std::endl;
    }
    void OpenForWrite(){
        _fd = open(_fifoname.c_str(),O_WRONLY);
        if(_fd<0)
        {
            std::cout<<"open file file!"<<std::endl;
        }
        std::cout<<"open file success!"<<std::endl;
    }
    void Read(){
        while(true)
        {
            char buffer[1024];
            int n = read(_fd,buffer,sizeof(buffer)-1);
            if(n>0)
            {
                buffer[n]=0;
                std::cout<<"client say: "<<buffer<<std::endl;
            }
            else if(n==0)
            {
                std::cout<<"stop"<<std::endl;
                break;
            }
            else{
                std::cout<<"read error"<<std::endl;
                break;
            }

        }
    }
    void Write(){
        std::string message;
        int cnt = 1;
        pid_t id = getpid();
        while(true)
        {
            std::cout<<"Please Entry:";
            std::getline(std::cin,message);
            message += (", message number: " + std::to_string(cnt++) + ", [" + std::to_string(id) + "]");
            write(_fd,message.c_str(),message.size());
        }
    }
    void Close()
    {
        if(_fd>0)
        close(_fd);
    }
    ~Fifo_oper(){}
private:
    std::string _filename;
    std::string _path;
    std::string _fifoname;
    int _fd;
};